package com.frogs.ucenter.dao.ibatis;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Repository;

import com.frogs.framework.base.dao.ibatis.BaseDaoIbatis;
import com.frogs.framework.util.StringUtil;
import com.frogs.ucenter.dao.AreaInfoDao;
import com.frogs.ucenter.entity.AreaInfo;
import com.ibatis.sqlmap.client.SqlMapClient;

@Repository("areaInfoDao")
public class AreaInfoDaoImpl extends BaseDaoIbatis<AreaInfo> implements AreaInfoDao {

	public AreaInfoDaoImpl() {
		super();
		setNameSpace("area_code");
	}

	@Required
	@Autowired
	public void setSqlMapClientAutowired(SqlMapClient sqlMapClient) {
		super.setSqlMapClient(sqlMapClient);
	}

	@Override
	public List<Map<String, String>> getSubAreaList(String parentId) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		int areaLength = parentId.length();
		if ("0".equalsIgnoreCase(parentId)) {
			areaLength = 2;
		} else {
			if (areaLength != 6) {
				areaLength += 2;
			}
		}
		try {
			param.put("parentId", parentId);
			param.put("areaLength", areaLength);
			SqlMapClient sqlMapClient = getSqlMapClientTemplate().getSqlMapClient();
			return sqlMapClient.queryForList(getNameSpace() + ".listSubArea", param);
		} catch (SQLException e) {
			throw new Exception("获取子地区出错，出错信息：" + e.getMessage());
		}
	}

	@Override
	public List<String> getPostCode(String address, String areaCode) throws Exception {
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			String mainAddress = "";
			if (address.length() > 3) {
				mainAddress = address.substring(0, 3);
				param.put("address", mainAddress);
			} else {
				param.put("address", address);
			}
			param.put("areaCode", areaCode);
			SqlMapClient sqlMapClient = getSqlMapClientTemplate().getSqlMapClient();
			return sqlMapClient.queryForList(getNameSpace() + ".getPostCode", param);
		} catch (Exception e) {
			throw new Exception("查询出错！出错信息：" + e.getMessage());
		}
	}

	@Override
	public AreaInfo showArea(String province, String city, String district) {
		Map<String,Object> params = new HashMap<String,Object>();
		if(!StringUtil.isEmpty(province)) {
			params.put("likeProvince", province);
		}
		if(!StringUtil.isEmpty(city)) {
			params.put("likeCity", city);
		}
		if(!StringUtil.isEmpty(district)) {
			params.put("likeDistrict", district);
		}
		if(!params.isEmpty()) {
			List<AreaInfo> areaList = selectByMap(params, 1, 1);
			if(areaList.size() != 0) {
				return areaList.get(0);
			}
		}
		return null;
	}
}